<template>
  <el-dialog :title="action === 'add' ? '新增' : '修改'" width="30%" draggable
              :close-on-click-modal="false" v-model="visible" @open="submitted = false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit(dataFormRef)" label-width="80px">
      <el-form-item label="父级资源">
        <el-input v-model="dataForm.pname" readonly />
      </el-form-item>
      <el-form-item v-if="type === 'request'" label="资源代码" prop="code">
        <el-input v-model="dataForm.code" minlength="2" maxlength="50" show-word-limit placeholder="资源代码" @change="codeChangeEvent" />
      </el-form-item>
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="dataForm.name" minlength="2" maxlength="20" show-word-limit placeholder="资源名称" />
      </el-form-item>
      <el-form-item v-if="type === 'menu'" label="菜单类型" prop="type">
        <el-select v-model="dataForm.type" placeholder="请选择菜单类型">
          <el-option label="目录" value="M"></el-option>
          <el-option label="页面" value="P"></el-option>
          <el-option label="集成页面" value="I"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 'M'" label="资源地址" prop="url">
        <el-input v-model="dataForm.url" maxlength="100" show-word-limit placeholder="资源地址" />
      </el-form-item>
      <el-form-item v-if="type === 'menu'" label="菜单图标" prop="icon">
        <icon-select v-model="dataForm.icon"></icon-select>
      </el-form-item>
      <el-form-item v-if="type === 'menu'" label="菜单排序" prop="sort">
        <el-input-number v-model="dataForm.sort" :min="1" :max="10000" label="菜单排序" />
      </el-form-item>
      <el-form-item v-if="type === 'request'" label="备注" prop="description">
        <el-input type="textarea" v-model="dataForm.description" maxlength="100" show-word-limit placeholder="备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="submitted">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import type { FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";

import IconSelect from "@/components/icon-svg/icon-select.vue";

// 类型：menu-菜单，request：请求
const type = ref("");

// 操作：add-新增，update-修改
const action = ref("");

// 弹窗是否显示
const visible = ref(false);

// 提交按钮是否禁用
const submitted = ref(false);

// 表单数据
const dataForm = reactive({
  id: undefined,
  pid: undefined,
  pname: "",
  code: "",
  name: "",
  type: "",
  url: "",
  sort: undefined,
  icon: "",
  description: "",
});

//表单校验规则
const dataRule = reactive({
  code: validate.required("资源代码"),
  name: validate.required("资源名称"),
  type: validate.required("菜单类型"),
  url: validate.required("资源地址"),
  icon: validate.required("菜单图标"),
  sort: validate.required("菜单排序"),
});

// 表单引用
const dataFormRef = ref<FormInstance>();

// 父级组件的自定义事件
const emit = defineEmits(['initMenuData', 'initRequestData']);

// 表单初始化
const initForm = async (a, t, n) => {
  type.value = t;
  action.value = a;
  // 新增跟节点菜单
  if (a === "add-root" && t === "menu") {
    visible.value = true;
    await nextTick();
    dataFormRef.value.resetFields();
    resetDataForm();
    dataForm.id = undefined;
    dataForm.pid = undefined;
    dataForm.pname = "跟节点";
    dataForm.type = "M";
    dataForm.sort = (n && n.length > 0 && n[n.length - 1].sort + 1) || 1;
    return;
  }
  // 新增子节点菜单
  if (a === "add-node" && t === "menu") {
    visible.value = true;
    await nextTick();
    dataFormRef.value.resetFields();
    resetDataForm();
    dataForm.id = undefined;
    dataForm.pid = n && n.id;
    dataForm.pname = n && n.name;
    dataForm.type = "M";
    dataForm.sort = (n.children && n.children.length > 0 && n.children[n.children.length - 1].sort + 1) || 1;
    return;
  }
  // 请求新增操作
  if (a === "add-node" && t === "request") {
    visible.value = true;
    await nextTick();
    dataFormRef.value.resetFields();
    resetDataForm();
    dataForm.id = undefined;
    dataForm.pid = n && n.id;
    dataForm.pname = (n && n.name) || "跟节点";
    dataForm.type = "R";
    return;
  }
  // 修改操作
  dataForm.id = n.id;
  http
    .post({
      url: "/resource/info",
      params: { resourceId: dataForm.id },
    })
    .then(async ({ data }) => {
      if (http.success(data)) {
        visible.value = true;
        await nextTick();
        dataFormRef.value.resetFields();
        resetDataForm();
        dataForm.id = data.body.id;
        dataForm.pid = data.body.pid;
        dataForm.pname = data.body.pname;
        dataForm.code = data.body.code;
        dataForm.name = data.body.name;
        dataForm.type = data.body.type;
        dataForm.url = data.body.url;
        dataForm.sort = data.body.sort;
        dataForm.icon = data.body.icon;
        dataForm.description = data.body.description;
      }
    });
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (submitted.value) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      submitted.value = true;
      http
        .post({
          url: "/resource/save",
          data: {
            id: dataForm.id || undefined,
            pid: dataForm.pid,
            code: dataForm.code || undefined,
            name: dataForm.name || undefined,
            url: dataForm.url || undefined,
            type: dataForm.type || undefined,
            sort: dataForm.sort || undefined,
            icon: dataForm.icon || undefined,
            description: dataForm.description || undefined,
          },
        })
        .then(async ({ data }) => {
          if (http.success(data, true, true)) {
            visible.value = false;
            if (type.value === "menu") {
              emit("initMenuData");
            } else {
              emit("initRequestData");
            }
            return;
          }
          submitted.value = false;
        });
    }
  });
};

// 清空表单
const resetDataForm = () => {
  dataForm.id = undefined;
  dataForm.pid = undefined;
  dataForm.pname = "";
  dataForm.code = "";
  dataForm.name = "";
  dataForm.type = "";
  dataForm.url = "";
  dataForm.sort = undefined;
  dataForm.icon = "";
  dataForm.description = "";
};

// 资源代码变化事件
const codeChangeEvent = (val) => {
  if (val && !dataForm.url) {
    dataForm.url = "/" + val.replaceAll(":", "/");
  }
};

// 暴露方法
defineExpose({ initForm });
</script>
